{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## MLP network for MNIST digits classification\n",
    "~98.3% test accuracy in 20epochs if adam\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential_2\"\n",
      "_________________________________________________________________\n",
      "Layer (type)                 Output Shape              Param #   \n",
      "=================================================================\n",
      "dense_4 (Dense)              (None, 256)               200960    \n",
      "_________________________________________________________________\n",
      "activation_4 (Activation)    (None, 256)               0         \n",
      "_________________________________________________________________\n",
      "dropout_3 (Dropout)          (None, 256)               0         \n",
      "_________________________________________________________________\n",
      "dense_5 (Dense)              (None, 256)               65792     \n",
      "_________________________________________________________________\n",
      "activation_5 (Activation)    (None, 256)               0         \n",
      "_________________________________________________________________\n",
      "dropout_4 (Dropout)          (None, 256)               0         \n",
      "_________________________________________________________________\n",
      "dense_6 (Dense)              (None, 10)                2570      \n",
      "_________________________________________________________________\n",
      "activation_6 (Activation)    (None, 10)                0         \n",
      "=================================================================\n",
      "Total params: 269,322\n",
      "Trainable params: 269,322\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n",
      "Epoch 1/20\n",
      "60000/60000 [==============================] - 2s 29us/step - loss: 1.6048 - acc: 0.4758\n",
      "Epoch 2/20\n",
      "60000/60000 [==============================] - 2s 27us/step - loss: 0.8429 - acc: 0.7332\n",
      "Epoch 3/20\n",
      "60000/60000 [==============================] - 2s 28us/step - loss: 0.6521 - acc: 0.7994\n",
      "Epoch 4/20\n",
      "60000/60000 [==============================] - 2s 27us/step - loss: 0.5541 - acc: 0.8319\n",
      "Epoch 5/20\n",
      "60000/60000 [==============================] - 2s 27us/step - loss: 0.4978 - acc: 0.8502\n",
      "Epoch 6/20\n",
      "60000/60000 [==============================] - 2s 28us/step - loss: 0.4557 - acc: 0.8631\n",
      "Epoch 7/20\n",
      "60000/60000 [==============================] - 1s 24us/step - loss: 0.4248 - acc: 0.8727\n",
      "Epoch 8/20\n",
      "60000/60000 [==============================] - 1s 23us/step - loss: 0.4030 - acc: 0.8806\n",
      "Epoch 9/20\n",
      "60000/60000 [==============================] - 1s 24us/step - loss: 0.3787 - acc: 0.8878\n",
      "Epoch 10/20\n",
      "60000/60000 [==============================] - 1s 25us/step - loss: 0.3631 - acc: 0.8924\n",
      "Epoch 11/20\n",
      "60000/60000 [==============================] - 2s 29us/step - loss: 0.3475 - acc: 0.8968\n",
      "Epoch 12/20\n",
      "60000/60000 [==============================] - 2s 28us/step - loss: 0.3307 - acc: 0.9020\n",
      "Epoch 13/20\n",
      "60000/60000 [==============================] - 2s 30us/step - loss: 0.3185 - acc: 0.9061\n",
      "Epoch 14/20\n",
      "60000/60000 [==============================] - 2s 29us/step - loss: 0.3102 - acc: 0.9105\n",
      "Epoch 15/20\n",
      "60000/60000 [==============================] - 2s 26us/step - loss: 0.2961 - acc: 0.9124\n",
      "Epoch 16/20\n",
      "60000/60000 [==============================] - 2s 26us/step - loss: 0.2887 - acc: 0.9148\n",
      "Epoch 17/20\n",
      "60000/60000 [==============================] - 2s 27us/step - loss: 0.2822 - acc: 0.9181\n",
      "Epoch 18/20\n",
      "60000/60000 [==============================] - 1s 24us/step - loss: 0.2706 - acc: 0.9218\n",
      "Epoch 19/20\n",
      "60000/60000 [==============================] - 2s 26us/step - loss: 0.2650 - acc: 0.9221\n",
      "Epoch 20/20\n",
      "60000/60000 [==============================] - 2s 27us/step - loss: 0.2610 - acc: 0.9234\n",
      "10000/10000 [==============================] - 0s 13us/step\n",
      "\n",
      "Test accuracy: 94.8%\n"
     ]
    }
   ],
   "source": [
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import numpy as np\n",
    "from keras.models import Sequential\n",
    "from keras.layers import Dense, Activation, Dropout\n",
    "from keras.utils import to_categorical, plot_model\n",
    "from keras.datasets import mnist\n",
    "\n",
    "# load mnist dataset\n",
    "(x_train, y_train), (x_test, y_test) = mnist.load_data()\n",
    "\n",
    "# compute the number of labels\n",
    "num_labels = len(np.unique(y_train))\n",
    "\n",
    "# convert to one-hot vector\n",
    "# e.g. 3 -> [0 0 0 1 0 0 0 0 0 0]\n",
    "y_train = to_categorical(y_train)\n",
    "y_test = to_categorical(y_test)\n",
    "\n",
    "# image dimensions (assumed square)\n",
    "image_size = x_train.shape[1]\n",
    "input_size = image_size * image_size\n",
    "\n",
    "# resize and normalize\n",
    "x_train = np.reshape(x_train, [-1, input_size])\n",
    "x_train = x_train.astype('float32') / 255\n",
    "x_test = np.reshape(x_test, [-1, input_size])\n",
    "x_test = x_test.astype('float32') / 255\n",
    "\n",
    "# network parameters\n",
    "batch_size = 128\n",
    "hidden_units = 256\n",
    "dropout = 0.45\n",
    "\n",
    "# model is a 3-layer MLP with ReLU and dropout after each layer\n",
    "model = Sequential()\n",
    "model.add(Dense(hidden_units, input_dim=input_size))\n",
    "model.add(Activation('relu'))\n",
    "model.add(Dropout(dropout))\n",
    "model.add(Dense(hidden_units))\n",
    "model.add(Activation('relu'))\n",
    "model.add(Dropout(dropout))\n",
    "model.add(Dense(num_labels))\n",
    "# this is the output for one-hot vector\n",
    "model.add(Activation('softmax'))\n",
    "model.summary()\n",
    "# plot_model(model, to_file='mlp-mnist.png', show_shapes=True)\n",
    "\n",
    "# loss function for one-hot vector\n",
    "# use of sgd optimizer with default lr=0.01\n",
    "# accuracy is good metric for classification tasks\n",
    "model.compile(loss='categorical_crossentropy',\n",
    "              optimizer='sgd',\n",
    "              metrics=['accuracy'])\n",
    "# train the network\n",
    "model.fit(x_train, y_train, epochs=20, batch_size=batch_size)\n",
    "\n",
    "# validate the model on test dataset to determine generalization\n",
    "loss, acc = model.evaluate(x_test, y_test, batch_size=batch_size)\n",
    "print(\"\\nTest accuracy: %.1f%%\" % (100.0 * acc))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
